<template>
  <div class="app-container">
    <el-card v-loading.fullscreen.lock="fullscreenLoading">
      <el-row>
        <el-col :md="10">
          <el-upload
            ref="upload"
            accept=".xml"
            :headers="headers"
            :action="`${host}/practice/problem/uploadProblem`"
            :on-success="successXml"
            :on-error="errorXml"
            :before-upload="uploadBefore"
            :limit="1"
            :auto-upload="false"
          >
            <el-button slot="trigger" type="primary">选取文件</el-button>
            <el-button style="margin-left: 3rem;" type="success" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" style="color: #F56C6C;margin-top: 0.5rem">只能上传单个不大于20M的xml文件</div>
          </el-upload>
        </el-col>
        <el-col :md="7">
          <div style="margin-top: 1rem">
            更多题目请
            <el-link style="font-size: 17px" href="http://tk.hustoj.com/problemset.php?search=free" target="_blank" type="primary">点击</el-link>
          </div>
        </el-col>
        <el-col :md="7">
          <el-button type="primary" :loading="loading" @click="downloadProblem">下载题目</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-drawer
      title="导入结果"
      :visible.sync="drawer"
      direction="ttb"
      :before-close="handleClose"
      :destroy-on-close="true"
      size="80%"
    >
      <el-row>
        <el-card :span="24" style="overflow: scroll;height: 70vh;">
          <el-alert
            v-for="result in results"
            :key="result.title"
            style="margin-bottom: 0.5rem"
            :title="result.flag?result.title+'：导入成功':result.title+'：导入失败'"
            :type="result.flag?'success':'error'"
            center
            effect="dark"
            :closable="false"
            show-icon
          />
        </el-card>
      </el-row>
    </el-drawer>
    <el-card style="margin-top: 1rem">
      <el-table
        ref="problem"
        :data="tableData"
        stripe
        :default-sort="{prop: 'problemId', order: 'ascending'}"
        @sort-change="headerClick"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="problemId" label="编号" sortable />
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="inDate" label="添加时间" sortable />
        <el-table-column prop="classifyName" label="来源" />
      </el-table>
      <el-pagination
        style="margin-top: 20px;"
        background
        :current-page="currentPage"
        :page-sizes="[10, 25, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script>
import { getToken, getUserId } from '@/utils/auth'
import { simpleProblemPage } from '@/api/problem'
import { saveAs } from 'file-saver'
import axios from 'axios'

export default {
  data() {
    return {
      host: process.env.VUE_APP_BASE_API,
      drawer: false,
      fullscreenLoading: false,
      results: [],
      headers: {
        Authorization: getToken(),
        user_id: getUserId()
      },
      currentPage: 1,
      pageSize: 10,
      totalNum: 0,
      sort: 1,
      tableData: [],
      multipleSelection: [],
      loading: false
    }
  },
  created() {
    this.simpleProblemPage()
  },
  methods: {
    downloadProblem() {
      const problemIds = this.multipleSelection.map(t => t.problemId).toString()
      if (problemIds.length < 1) {
        this.$message.info('请选择题目')
        return
      }
      this.loading = true
      this.$message.success('下载即将开始，请稍后')
      axios({
        method: 'get',
        url: this.host + '/practice/problem/downloadProblem',
        params: { problemIds: problemIds },
        headers: this.headers
      }).then(res => {
        this.loading = false
        const blob = new Blob([res.data], { type: 'text/xml;charset=utf-8' })
        saveAs(blob, 'Problems.xml')
      }).catch(() => { this.loading = false })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    simpleProblemPage() {
      simpleProblemPage({
        current: this.currentPage,
        size: this.pageSize,
        sort: this.sort }).then(res => {
        this.totalNum = Number(res.data.total)
        this.tableData = res.data.records
      })
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.simpleProblemPage()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.simpleProblemPage()
    },
    headerClick(event) {
      const params = [['problemId', 1], ['inDate', 3]]
      const sortMap = new Map(params)
      if (event.order === null) {
        this.sort = 0
        this.simpleProblemPage()
        return
      }
      if (event.order === 'descending') {
        sortMap.set(event.prop, sortMap.get(event.prop) + 1)
      }
      this.sort = sortMap.get(event.prop)
      this.simpleProblemPage()
    },
    submitUpload() {
      if (this.$refs.upload.uploadFiles.length < 1) {
        this.$message.warning('还没选择文件呢')
        return
      }
      this.$refs.upload.submit()
    },
    successXml(response, file, fileList) {
      if (response.code === '00000') {
        this.$message({ message: response.message, type: 'success' })
        this.results = response.data
        this.drawer = true
      } else {
        this.$message({ message: response.message, type: 'error' })
      }
      this.fullscreenLoading = false
    },
    uploadBefore(file) {
      if (file.size > 20971520) {
        this.$message.warning('文件上限为20M')
        return false
      } else if (file.type !== 'text/xml') {
        this.$message.warning('文件类型为xml')
        return false
      } else {
        this.fullscreenLoading = true
        return true
      }
    },
    errorXml(response, file, fileList) {
      this.fullscreenLoading = false
      this.$message({ message: response.message, type: 'error' })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    }
  }
}
</script>

<style scoped>

</style>
